<template>
  <div class="usedMachine container">
    <!-- 设备筛选 -->
    <section class="used-machine-filter container">
      <div class="change-box">
        <div class="filter">
          <div class="filter-left">{{ $t("category") }}</div>
          <div class="filter-right">
            <a
              :class="[typeId == item.id ? 'selected-item' : 'select-item']"
              v-for="item in typeList"
              :key="item.id"
              :href="`/used-machine/${$optionsData.equipmentTypePy[item.id]}-${item.id}`"
              :title="item.name"
              @click="numSelectType"
              >{{ item.name }}</a
            >
          </div>
        </div>
        <div class="filter" v-if="locale == 'zh-CN'">
          <div class="filter-left">区域</div>
          <div class="filter-right">
            <span
              :class="[areaId == item.code ? 'selected-item' : 'select-item']"
              v-for="item in $optionsData.provinceList"
              :key="item.code"
              @click="numSelectArea(item.code)"
              >{{ item.text }}</span
            >
          </div>
        </div>
        <div class="filter" v-for="item in attrsList" :key="item.title">
          <div class="filter-left">{{ item.title }}</div>
          <div class="filter-right">
            <span
              :class="[val.checked ? 'selected-item' : 'select-item']"
              v-for="(val, index) in item.options"
              :key="val.value"
              @click="selectTem(item.title, index)"
              >{{ val.name }}</span
            >
          </div>
        </div>
      </div>
    </section>
    <!-- 设备列表 -->
    <section class="equipment-list container">
      <template v-if="equipmentList.length">
        <a
          class="equipment-item"
          v-for="item in equipmentList"
          :key="item.crmEquipmentId"
          :href="`/equipment/${item.typeNameEn}-${item.crmEquipmentId}`"
          :title="`${item.title} | ${item.subHeading}`"
          @click="handleDetail"
        >
          <el-image class="info-img" fit="cover" :src="item.thumbnail" lazy :alt="item.title"></el-image>
          <div class="info-bottom">
            <div class="info-title">{{ item.title }}</div>
            <div class="info-year">{{ item.subHeading }}</div>
            <div class="info-tag" v-if="locale == 'zh-CN'">
              <p v-for="val in item.targerList" :key="val">{{ val }}</p>
            </div>
            <div style="height: 18px" v-else></div>
            <div class="info-price">
              <template v-if="item.crmEquipmentFixedPriceId && item.offlineBargaining != 1">
                <p v-if="locale == 'en-US'">CNY{{ item.startingPriceNotag }}</p>
                <p v-else>{{ item.startingPrice / 1000000 }}万</p>
              </template>
              <p v-else>{{ $t("priceNegotiable") }}</p>
            </div>
          </div>
        </a>
      </template>
      <div class="no-data" v-else>
        <div class="no-pic">
          <img class="pic-empty" src="https://yunlian-oss-product.oss-cn-hangzhou.aliyuncs.com/website/pic-empty.png" />
          <p>{{ $t("noListingsFound") }}</p>
        </div>
        <a class="help-car" href="/find-car" :title="`${$t('findMachine')}`">{{ $t("findMachine") }}</a>
      </div>
    </section>
    <!-- 分页器 -->
    <section class="container" v-if="equipmentList.length">
      <TablePage ref="list" @page-change="getEquipmentListData" :total="total" :pageSizeNum="pageSizeNum"> </TablePage>
    </section>
    <!-- 侧边栏服务 -->
    <Dangling v-if="locale == 'zh-CN'" />
    <!-- WhatsApp -->
    <!-- <WhatsApp v-if="locale == 'en-US'" /> -->
    <!-- 在线客服 -->
    <Connect />
  </div>
</template>

<script>
import { mapState } from "vuex"
import BigNumber from "bignumber.js"
export default {
  name: "UsedMachine",
  layout: "Layout",
  data() {
    return {}
  },
  head() {
    return {
      title: this.$i18n.t("headTitle"),
      meta: [
        {
          hid: "keywords",
          name: "keywords",
          content: this.$i18n.t("haeaKeyContent")
        },
        {
          hid: "description",
          name: "description",
          content: this.$i18n.t("haeaDecContent")
        }
      ]
    }
  },
  async asyncData({ app, params }) {
    let paramsRes = params.typeParams.split("-")
    console.log("paramsRes", paramsRes)
    let total = 0
    let pageSizeNum = 16
    let typeId = paramsRes[1] //设备类型ID
    let areaId = paramsRes[2] || "" //区域ID
    let typeList = []
    let attrsList = []
    let equipmentList = []
    let tonnageName = ""
    let yearsName = ""
    let workingHoursName = ""
    let batchNumName = ""
    let armSpanName = ""
    try {
      if (app.$cookies.get("msgInfo") && !!app.$cookies.get("searchCondition")) {
        let data = app.$cookies.get("searchCondition")
        typeId = data[0].typeId
        areaId = data[0].areaId
        tonnageName = data[0].tonnageName
        yearsName = data[0].yearsName
        workingHoursName = data[0].workingHoursName
        batchNumName = data[0].batchNumName
        armSpanName = data[0].armSpanName
        attrsList = data[1]
      } else {
        app.$cookies.remove("searchCondition")
        //筛选-模板
        let configRes = await app.$api.searchConfig({ typeId: typeId })
        attrsList = configRes.data && configRes.data.cardList ? configRes.data.cardList[0].attrs : []
      }
      //设备机型
      let typeRes = await app.$api.machineType()
      typeList = typeRes.data || []
      //设备列表
      const equipmentParams = {
        pageNo: 1,
        pageSize: pageSizeNum,
        search: {
          typeId: typeId,
          provinceCodes: [areaId || 100000],
          tonnageName: tonnageName,
          yearsName: yearsName,
          workingHoursName: workingHoursName,
          batchNumName: batchNumName,
          armSpanName: armSpanName
        }
      }
      let { data } = await app.$api.equipmentList(equipmentParams)
      equipmentList = (data.list || []).map((item) => {
        item.startingPriceNotag = new BigNumber(item.startingPrice).dividedBy(100).toFormat()
        let targerList = app.$optionsData.parseLabel(item)
        if (targerList.indexOf("寄售") != -1) {
          targerList.splice(targerList.indexOf("寄售"), 1)
        }
        targerList = targerList.splice(0, 2)
        item["targerList"] = targerList
        return item
      })
      total = data.total
    } catch (error) {
      console.log(error)
    }
    return {
      total,
      pageSizeNum,
      equipmentList, //设备列表
      typeId, //设备类型-筛选
      areaId, //区域-筛选
      typeList, //设备类型列表
      attrsList, //筛选模板列表
      tonnageName, //吨位筛选
      yearsName, //年限筛选
      workingHoursName, //小时数筛选
      batchNumName, //批量数筛选
      armSpanName //臂展长度筛选
    }
  },
  props: {},
  computed: { ...mapState(["locale"]) },
  async mounted() {
    this.getPoint()
  },
  destroyed() {
    this.$cookies.remove("msgInfo") //清除检索存储值
  },
  methods: {
    //初始化查询
    searchHandler() {
      this.$refs.list.reset()
    },
    // 类型筛选
    numSelectType() {
      this.$cookies.remove("msgInfo") //清除检索存储值
    },
    // 区域筛选
    numSelectArea(val) {
      this.areaId = this.areaId != val ? val : ""
      this.getEquipmentListData(1, 16)
    },
    selectTem(title, index) {
      let list = this.attrsList
      for (let i = 0; i < list.length; i++) {
        for (let j = 0; j < list[i].options.length; j++) {
          if (list[i].title == title) {
            if (j == index) {
              if (list[i].options[j].checked == true) {
                list[i].options[j].checked = false
                if (title == "出厂年限" || title == "Factory Years") {
                  this.yearsName = ""
                } else if (title == "表显小时数" || title == "Meter display hours") {
                  this.workingHoursName = ""
                } else if (title == "吨位" || title == "起重总量" || title == "Tonnage" || title == "Total lifting capacity") {
                  this.tonnageName = ""
                } else if (title == "批量数" || title == "Batch quantity") {
                  this.batchNumName = ""
                } else if (title == "臂架长度" || title == "Arm length") {
                  this.armSpanName = ""
                }
              } else {
                list[i].options[j].checked = true
                if (title == "出厂年限" || title == "Factory Years") {
                  this.yearsName = list[i].options[j].value
                } else if (title == "表显小时数" || title == "Meter display hours") {
                  this.workingHoursName = list[i].options[j].value
                } else if (title == "吨位" || title == "起重总量" || title == "Tonnage" || title == "Total lifting capacity") {
                  this.tonnageName = list[i].options[j].value
                } else if (title == "批量数" || title == "Batch quantity") {
                  this.batchNumName = list[i].options[j].value
                } else if (title == "臂架长度" || title == "Batch quantity") {
                  this.armSpanName = list[i].options[j].value
                }
              }
            } else {
              list[i].options[j].checked = false
            }
          }
        }
      }
      this.attrsList = list
      this.$forceUpdate()
      this.getEquipmentListData(1, 16)
    },
    async getEquipmentListData(page, pageSize) {
      const params = {
        pageNo: page,
        pageSize: pageSize,
        search: {
          typeId: this.typeId,
          provinceCodes: [this.areaId || 100000],
          tonnageName: this.tonnageName,
          yearsName: this.yearsName,
          workingHoursName: this.workingHoursName,
          batchNumName: this.batchNumName,
          armSpanName: this.armSpanName
        }
      }
      try {
        let {
          data: { list, total }
        } = await this.$api.equipmentList(params)
        this.equipmentList = (list || []).map((item) => {
          item.startingPriceNotag = new BigNumber(item.startingPrice).dividedBy(100).toFormat()
          let targerList = this.$optionsData.parseLabel(item)
          if (targerList.indexOf("寄售") != -1) {
            targerList.splice(targerList.indexOf("寄售"), 1)
          }
          targerList = targerList.splice(0, 2)
          item["targerList"] = targerList
          return item
        })
        this.total = total
      } catch (error) {
        console.log(error)
      }
    },
    handleDetail() {
      let storageData = {
        typeId: this.typeId,
        areaId: this.areaId,
        tonnageName: this.tonnageName,
        yearsName: this.yearsName,
        workingHoursName: this.workingHoursName,
        batchNumName: this.batchNumName,
        armSpanName: this.armSpanName
      }
      this.$cookies.set("searchCondition", JSON.stringify([storageData, this.attrsList])) //存储搜索条件
    },
    async getPoint() {
      let params = await this.$optionPoint.sendUrl(window, navigator, document)
      this.$api.burySave({ ...params }).then((res) => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.usedMachine {
  display: flex;
  flex-direction: column;
  .used-machine-filter {
    height: 100%;
    background: #f6f7f9;
    margin-top: 20px;
    .change-box {
      padding: 0 20px;
      box-sizing: border-box;
      .filter {
        padding: 10px 0;
        border-bottom: 1px solid #efeff4;
        display: flex;
        align-items: center;
        .filter-left {
          min-width: 70px;
          font-size: 14px;
          font-weight: 500;
          color: #999;
          padding-right: 24px;
          border-right: 1px solid #efeff4;
          flex: none;
        }
        .filter-right {
          display: flex;
          flex-flow: wrap;
          .selected-item {
            padding: 8px 10px;
            font-size: 14px;
            font-weight: 500;
            color: #fb463f;
            background: rgba(251, 70, 63, 0.08);
            margin-right: 10px;
            border-radius: 4px;
            cursor: pointer;
          }
          .select-item {
            padding: 8px 10px;
            font-size: 14px;
            font-weight: 500;
            color: #333;
            margin-right: 10px;
            cursor: pointer;
          }
        }
      }
    }
  }
  .equipment-list {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    height: 100%;
    margin-top: 20px;
    .equipment-item {
      width: 290px;
      height: 100%;
      margin-bottom: 20px;
      .info-img {
        width: 290px;
        height: 184px;
        display: block;
      }
      .info-bottom {
        width: 100%;
        height: 116px;
        background: #f6f7f9;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        padding: 10px;
        box-sizing: border-box;
        .info-title {
          font-family: PingFangSC, PingFang SC;
          font-weight: 500;
          font-size: 18px;
          color: #333;
          line-height: 22px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .info-year {
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 14px;
          color: #999;
          line-height: 16px;
        }
        .info-tag {
          display: flex;
          align-items: center;
          p {
            height: 18px;
            line-height: 18px;
            padding: 2px 5px;
            border-radius: 4px;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 12px;
            color: #fb463f;
            background: rgba(251, 70, 63, 0.08);
            margin-right: 5px;
          }
        }
        .info-price {
          display: flex;
          align-items: flex-end;
          flex-direction: row;
          justify-content: space-between;
          p {
            font-size: 16px;
            font-weight: 700;
            color: #fb463f;
          }
        }
      }
      &:last-child:nth-child(4n - 1) {
        margin-right: calc(24% + 4% / 3);
      }
      &:last-child:nth-child(4n - 2) {
        margin-right: calc(48% + 8% / 3);
      }
      &:hover {
        box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.2);
        .info-bottom {
          background: #fff;
        }
      }
    }
    .no-data {
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-bottom: 40px;
      .no-pic {
        .pic-empty {
          width: 300px;
          height: 197px;
        }
        p {
          font-size: 16px;
          font-weight: 400;
          color: #666666;
          line-height: 18px;
          margin-top: 10px;
          text-align: center;
        }
      }
      .help-car {
        width: 140px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background: #fb463f;
        border-radius: 4px;
        font-size: 16px;
        font-weight: 500;
        color: #fff;
        margin-top: 30px;
      }
    }
  }
}
</style>
